import React, {useEffect, useState} from 'react'
import {Button, Space, message, Cascader, TreeSelect, Popover} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {history, connect} from 'umi'
import {
	PlusOutlined,
	ArrowUpOutlined,
	ArrowDownOutlined,
} from '@ant-design/icons'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import Permissions from '@/components/Permissions'
import {
	deleteSupplierAccess,
	getImportSupplierBase,
	getImportSupplierCs,
	getImportSupplierDyy,
	getImportSupplierHandle,
	getImportSupplierSp,
	getSupplierAccessList,
	getSupplierBaseExcelList,
} from '@/service/supplier/supplierAccess'
import Modal from '@/components/Modal'
import {getSupplierType, translateDataToTree} from '@/utils/common'
import {getDict} from '@/service/common/dict'
import CustomTable from '@/components/Table'
import {getCompany} from '@/service/common'
import {modalApi} from '@/utils/modalReq'
import BatchUpload from './components/BatchUpload'
import {downloadDocumentUrl} from '@/service/common/download'

interface DataType {
	processInstanceId: any
	showAuditButton: any
	id: string
	supplierCode: string
	supplierName: string
	orgId: string
	serviceType: string
	contacts: string
	contactPhone: string
	auditResult: number | null
	status: number
}

const formItemLayout = {
	labelCol: {flex: '90px'},
	wrapperCol: {flex: '1'},
}
const fieldNames = {
	label: 'name',
	value: 'id',
	id: 'id',
	pId: 'parentId',
}

const admittance = (props: any) => {
	const [dataSourse, setDataSourse] = useState([])
	const [searchData, setSearchData] = useState({})
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
	const [id, setId] = useState<string>('')
	const [supplierTypeData, setSupplierTypeData] =
		useState<supplierAPI.supplierType>([])
	const [loading, setLoading] = useState<boolean>(false)
	const [companyData, setCompanyData] = useState([])
	const [total, setTotal] = useState()
	const [supplierType, setSupplierType] = useState<string>()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [uploadUrl, setUploadUrl] = useState('')
	const [sourceId, setSourceId] = useState<number>()
	const [templateType, setTemplateType] = useState('')

	const getImportData = () => {
		if (supplierType === 'sp渠道供应商') {
			return getImportSupplierSp
		}
		if (supplierType === '代运营资产方') {
			return getImportSupplierDyy
		}
		if (supplierType === '处置供应商') {
			return getImportSupplierHandle
		}
		if (supplierType === '车司平台') {
			return getImportSupplierCs
		}
		return getImportSupplierBase
	}

	useEffect(() => {
		if (supplierType) {
			if (supplierType === 'sp渠道供应商') {
				setUploadUrl(
					`${modalApi.supplier}/supplier/currency/checkSpData`,
				)
				setSourceId(26)
				setTemplateType('供应商准入导入模板（sp渠道供应商）')
			} else if (supplierType === '代运营资产方') {
				setUploadUrl(
					`${modalApi.supplier}/supplier/currency/checkDyyData`,
				)
				setSourceId(27)
				setTemplateType('供应商准入导入模板（代运营资产方）')
			} else if (supplierType === '处置供应商') {
				setUploadUrl(
					`${modalApi.supplier}/supplier/currency/checkHandleData`,
				)
				setSourceId(29)
				setTemplateType('供应商准入导入模板（处置供应商-出售类）')
			} else if (supplierType === '车司平台') {
				setUploadUrl(
					`${modalApi.supplier}/supplier/currency/checkCsData`,
				)
				setSourceId(30)
				setTemplateType('供应商准入导入模板（车司平台）')
			} else {
				setUploadUrl(
					`${modalApi.supplier}/supplier/currency/checkSupplierBase`,
				)
				setSourceId(28)
				setTemplateType('供应商准入导入模板（其他类型）')
			}
		}
	}, [supplierType])

	const onCompany = () => {
		getCompany({merchantId: props?.user?.orgId}).then((res: any) => {
			const list = translateDataToTree(res.data)
			setCompanyData(list as any)
		})
	}
	useEffect(() => {
		onCompany()
	}, [props?.user?.orgId])

	// 获取供应商准入列表
	const getData = () => {
		setLoading(true)
		getSupplierAccessList({...params, ...searchData})
			.then((res: any) => {
				if (res?.success) {
					setDataSourse(res?.data?.records)
					setTotal(res?.data?.total)
					setLoading(false)
				}
			})
			.catch((err) => {
				setDataSourse([])
				message.error(err)
				setLoading(false)
			})
	}
	useEffect(() => {
		getData()
	}, [params])

	useEffect(() => {
		getDict(
			{
				dictKeys: [
					'ZC_GYS',
					'JC_GYS',
					'CZ_GYS',
					'SP_GYS',
					'DYY_GYS',
					'CS_GYS',
				],
			},
			(res: any) => {
				// 组装供应商类型
				const newData = getSupplierType([
					res.ZC_GYS,
					res.JC_GYS,
					res.CZ_GYS,
					res.SP_GYS,
					res.DYY_GYS,
					res.CS_GYS,
				])
				setSupplierTypeData(newData)
			},
		)
	}, [])

	const deleteData = () => {
		deleteSupplierAccess(id)
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					setIsModalOpen(false)
					getData()
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}
	/** 拾取任务 */
	// const pickTask = (processInstanceId: string) => {
	// 	claimTaskCandidate({
	// 		reviewerId: props?.user?.userId,
	// 		processInstanceId,
	// 	})
	// }
	const columns: ColumnsType<DataType> = [
		{
			title: '供应商编号',
			dataIndex: 'supplierCode',
			align: 'center',
			width: 120,
		},
		{
			title: '供应商名称',
			dataIndex: 'supplierName',
			align: 'center',
			width: 160,
		},
		{
			title: '供应商所属公司',
			dataIndex: 'orgId',
			align: 'center',
			width: 140,
			ellipsis: true,
			render: (text) => (
				<>
					{text ? (
						<TreeSelect
							value={text?.split(',') || []}
							disabled
							multiple
							maxTagCount={3}
							maxTagPlaceholder="..."
							showCheckedStrategy="SHOW_ALL"
							dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
							treeDefaultExpandAll
							fieldNames={fieldNames}
							treeDataSimpleMode
							treeData={companyData}
						/>
					) : (
						'-'
					)}
				</>
			),
		},
		{
			title: '供应商类型',
			dataIndex: 'supplierType',
			align: 'center',
			width: 120,
			render: (text) => (
				<Cascader
					disabled
					value={text.split(',')}
					options={supplierTypeData}
				/>
			),
		},
		{
			title: '供应商联系人/电话',
			dataIndex: 'contactPhone',
			align: 'center',
			width: 160,
			render: (text) => <>{text || '-'}</>,
		},
		{
			title: '准入状态',
			dataIndex: 'auditResult',
			align: 'center',
			width: 100,
			render: (text) => {
				if (text === 1) {
					return '待审核'
				}
				if (text === 2) {
					return '审核中'
				}
				if (text === 3) {
					return '审核拒绝'
				}
				if (text === 4) {
					return '审核通过'
				}
				return ''
			},
		},
		{
			title: '准入日期',
			dataIndex: 'updateTime',
			align: 'center',
			width: 180,
			render: (text, record) => (
				<>
					{record?.auditResult === 4 && record.status === 1
						? text
						: '-'}
				</>
			),
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			width: 120,
			fixed: 'right',
			render: (text: any, record) => (
				<Space size={12}>
					<Permissions permissionID="amc_sppplier_admittance_view">
						<Button
							type="link"
							onClick={() => {
								history.push({
									pathname: '/supplier/admittance/view',
									query: {
										id: record?.id,
										processInstanceId:
											record?.processInstanceId,
									},
								})
							}}>
							详情
						</Button>
					</Permissions>
					{record.auditResult === 1 || record.auditResult === 3 ? (
						<Permissions permissionID="amc_sppplier_admittance_edit">
							<Button
								type="link"
								onClick={() => {
									history.push({
										pathname: '/supplier/admittance/edit',
										query: {
											id: record?.id,
										},
									})
								}}>
								编辑
							</Button>
						</Permissions>
					) : (
						''
					)}
					{record.auditResult === 3 ? (
						<Permissions permissionID="amc_sppplier_admittance_delete">
							<Button
								type="link"
								onClick={() => {
									setId(record?.id)
									setIsModalOpen(true)
								}}>
								删除
							</Button>
						</Permissions>
					) : (
						''
					)}
					{record?.showAuditButton ? (
						<Permissions permissionID="amc_sppplier_admittance_examine">
							<Button
								type="link"
								onClick={() => {
									// pickTask(record?.processInstanceId)
									history.push({
										pathname:
											'/supplier/admittance/process',
										query: {
											id: record?.id,
											examine: 'true',
											processInstanceId:
												record?.processInstanceId,
										},
									})
								}}>
								审核
							</Button>
						</Permissions>
					) : (
						''
					)}
				</Space>
			),
		},
	]
	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '供应商编号',
					name: 'supplierCode',
					key: 'supplierCode',
				},
				{
					type: 'input',
					label: '供应商名称',
					name: 'supplierName',
					key: 'supplierName',
				},
				{
					type: 'select',
					key: 'auditResult',
					name: 'auditResult',
					label: '准入状态',
					keys: 'value',
					title: 'title',
					items: [
						{
							value: 1,
							title: '待审核',
						},
						{
							value: 2,
							title: '审核中',
						},
						{
							value: 4,
							title: '审核通过',
						},
						{
							value: 3,
							title: '审核拒绝',
						},
					],
				},
			],
		},
	]
	const onFinish = (values: any) => {
		setSearchData(values)
		setParams({
			current: 1,
			size: 10,
		})
	}

	const onReset = () => {
		setSearchData({})
		setParams({
			current: 1,
			size: 10,
		})
	}

	const errorColumns: ColumnsType<DataType> = [
		{
			title: '供应商名称',
			dataIndex: 'supplierName',
			align: 'center',
			width: 120,
		},
		{
			title: '供应商类型',
			dataIndex: 'supplierType',
			align: 'center',
			width: 150,
		},
		{
			title: '统一社会信用代码',
			dataIndex: 'socialCreditCode',
			align: 'center',
			width: 150,
		},
		{
			title: '联系人',
			dataIndex: 'channelLeader',
			align: 'center',
			width: 150,
			render: (_text: any, record: any) => (
				<>
					{record?.channelLeader && (
						<span>{record?.channelLeader}</span>
					)}
					{record?.contacts && <span>{record?.contacts}</span>}
				</>
			),
		},
		{
			title: '联系人手机',
			dataIndex: 'leadingPhone',
			align: 'center',
			width: 150,
			render: (_text: any, record: any) => (
				<>
					{record?.leadingPhone && (
						<span>{record?.leadingPhone}</span>
					)}
					{record?.mobilePhone && <span>{record?.mobilePhone}</span>}
				</>
			),
		},
		{
			title: '失败原因',
			dataIndex: 'message',
			align: 'center',
			width: 200,
			ellipsis: true,
			render: (text: any) => (
				<Popover content={text}>
					<div
						style={{
							width: '200px',
							textOverflow: 'ellipsis',
							overflow: 'hidden',
							whiteSpace: 'nowrap',
						}}>
						{text}
					</div>
				</Popover>
			),
		},
	]

	return (
		<div className={styles.admittance}>
			<div className={styles.content}>
				<div className={styles.search}>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
					/>
				</div>
				<div className={styles.btnlist}>
					<Space size={12}>
						<Permissions permissionID="amc_sppplier_admittance_add">
							<Button
								icon={<PlusOutlined />}
								type="primary"
								ghost
								size="small"
								onClick={() => {
									history.push('/supplier/admittance/add')
								}}>
								新增准入
							</Button>
						</Permissions>
						<Permissions permissionID="amc_sppplier_admittance_import">
							<Button
								icon={<ArrowUpOutlined />}
								className={styles.warning}
								ghost
								size="small"
								onClick={() => setIsUploadModalOpen(true)}>
								导入
							</Button>
						</Permissions>
						<Permissions permissionID="amc_sppplier_admittance_export">
							<Button
								icon={<ArrowDownOutlined />}
								className={styles.import}
								ghost
								size="small"
								onClick={() => {
									downloadDocumentUrl({
										resourceId: '126',
										queryDesc:
											'供应商准入导出,resourceId:126',
										queryParam: searchData,
									})
								}}>
								导出
							</Button>
						</Permissions>
					</Space>
				</div>
				<CustomTable
					params={params}
					columns={columns}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
			<Modal
				text="确认要删除该数据吗？"
				onSubmit={deleteData}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
			<BatchUpload
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={getImportData()}
				onTableList={getSupplierBaseExcelList}
				getListData={getData}
				uploadFileUrl={uploadUrl}
				columns={errorColumns}
				supplierType={supplierType}
				setSupplierType={setSupplierType}
				sourceId={sourceId}
				templateType={templateType}
			/>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(admittance)
